package com.yc.cloud.admin.service.impl;

import com.yc.cloud.admin.config.MediaKitApiProperties;
import com.yc.cloud.admin.service.FFmpegStreamService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * FFmpeg流服务实现类
 * 
 * @author kinggu
 * @since 2025-01-XX
 */
@Slf4j
@Service
public class FFmpegStreamServiceImpl implements FFmpegStreamService {
    
    @Resource
    private MediaKitApiProperties mediaKitApiProperties;
    
    @Override
    public boolean checkStreamAvailable(String streamId) {
        try {
            MediaKitApiProperties.StreamConfig streamConfig = mediaKitApiProperties.getStream();
            String rtmpUrl = streamConfig.buildRtmpUrl(mediaKitApiProperties.getHost(), streamId);
            
            // 使用ffprobe简单检查流是否可用（最终优化版本）
            int timeoutSeconds = streamConfig.getCheckTimeoutSeconds();
            String[] command = {
                "ffprobe",
                "-v", "quiet",
                "-select_streams", "v:0",
                "-show_entries", "stream=codec_name",
                "-of", "csv=p=0",
                rtmpUrl
            };
            
            // 输出完整的执行命令，方便调试
            String fullCommand = String.join(" ", command);
            log.info("检查流可用性: streamId={}, URL={}, 超时时间={}秒", streamId, rtmpUrl, timeoutSeconds);
            log.info("完整执行命令: {}", fullCommand);
            
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();
            
            // 给进程等待时间比ffprobe超时时间多5秒
            boolean finished = process.waitFor(timeoutSeconds + 5, TimeUnit.SECONDS);
            if (!finished) {
                process.destroyForcibly();
                log.warn("检查流可用性超时: streamId={}", streamId);
                return false;
            }
            
            int exitCode = process.exitValue();
            boolean available = (exitCode == 0);
            
            // 读取命令输出用于调试
            try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream()))) {
                String line;
                StringBuilder output = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
                if (output.length() > 0) {
                    log.info("FFprobe输出: {}", output.toString().trim());
                }
            } catch (Exception e) {
                log.debug("读取FFprobe输出异常", e);
            }
            
            log.info("流可用性检查结果: streamId={}, available={}, exitCode={}", 
                    streamId, available, exitCode);
            
            return available;
            
        } catch (Exception e) {
            log.error("检查流可用性异常: streamId={}", streamId, e);
            return false;
        }
    }
}